//定义消息类型
// CONNECTED,SINGLE_SENDING,GROUP_SENDING;
var chatType={
    CONNECTED:0,
    SINGLE_SENDING:1,
    GROUP_SENDING:2
};
// 定义消息体
var msgFrame={
    from:"",
    to:"",
    content:"",
    ChatType:0
};

var userId=null;

var ws = new WebSocket('ws://localhost:8888/chat');
$(function () {
    ws.onopen = function() {
        console.log('CONNECT');
        showMsg('欢迎使用netty-chat')
    };
    ws.onclose = function() {
        console.log('DISCONNECT');
        showMsg('DISCONNECT')
    };
    ws.onmessage = function(event) {
        var msgFrame = event.data;
        console.log('MESSAGE: ' + event.data);
      var msgFrameObj =  JSON.parse(msgFrame);
      var content = "用户id"+msgFrameObj.from+"说了："+msgFrameObj.content;
        showMsg(content)
    };

});

function showMsg(content) {
    $("#console").append(content+"</br>");
}

function send(msgFrame) {
  var   msgFrameStr = JSON.stringify(msgFrame);
    console.log(msgFrameStr)
    ws.send(msgFrameStr)

}

function connect() {
    userId = $("#name").val();
    shaker(userId)
    showMsg("成功和服务端建立连接。。。")
}

function singleSend() {
    var msg =$("#msg").val();
    var to =$("#to").val();

    msgFrame.from=userId;
    msgFrame.to=to;
    msgFrame.ChatType=chatType.SINGLE_SENDING;
    msgFrame.content=msg;

    send(msgFrame)
    showMsg("我说了："+msg)
}

function shaker(from) {
    msgFrame.from=from;
    msgFrame.to=null;
    msgFrame.ChatType=chatType.CONNECTED;
    msgFrame.content='shaker';

    console.log(msgFrame)
    send(msgFrame);
}
